package pnu.ssm.service;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class ResurrectionService extends Service{
	
	public static final String TAG = "ResurrectionService";
	
	private final int breakTime = 5000; //10초
	private Timer timer;
	
	@Override
	public void onCreate(){
		super.onCreate();
		Log.d(TAG, "onCreate()");
		Toast.makeText(this,"Start ResurrectionService", Toast.LENGTH_LONG).show();
		timer = new Timer();
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		Log.d(TAG, "onDestroy()");
		Intent intent = new Intent();
		intent.setAction("pnu.ssm.intent.action.die.ResurrectionService");
		sendBroadcast(intent);
		Toast.makeText(this,"End RessurectionService", Toast.LENGTH_LONG).show();
		if(timer != null) timer.cancel();
	}
	
	@Override
	public int onStartCommand (Intent intent, int flags, int startId){
		super.onStartCommand(intent, flags, startId);
		Log.d(TAG, "onStartCommand()");
		timer.scheduleAtFixedRate(new ResureectionTimerTask(), 0, breakTime);
		return START_STICKY;
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	class ResureectionTimerTask extends TimerTask {
		@Override
		public void run() {
			Log.d(TAG, "ResurrectionService is running");
			String str = "pnu.ssm.sbchild";
			
			ActivityManager am = (ActivityManager)getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
			List<RunningAppProcessInfo> runningAppList = am.getRunningAppProcesses();
			boolean alive = false;
			
			for(RunningAppProcessInfo runningAppInfo : runningAppList){
				if(str.equalsIgnoreCase(runningAppInfo.processName)){
					alive = true;
					break;
				}
			}
			
			if(!alive){
				Intent intent;
				final String packageName = str;   
				intent = getApplication().getPackageManager().getLaunchIntentForPackage(packageName);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				getApplication().startActivity(intent);
			}
		}
	}
}
	
